#include <string.h>
#include <stddef.h>

#include "armsdkcli.h"
#include "armsdkerr.h"
#include "armsdkcmdhandle.h"
#include "armsdkcmdregister.h"
#include "uartglob.h"
#include "uartcmdregister.h"


INT4 adAPISdkCmdHandle(CHR *pu1CmdStr)
{
    INT4 i4Inc = 0;
    INT4 i4CmdId = 0;
    INT4 i4ArgNum = 0;
    INT4 i4Ret = FALSE;
    CHR  *pu1CmdWord[CMD_STR_WORDS] = {NULL};
    CHR  *pu1cmdArgs[CMD_STR_WORDS] = {NULL};

    for (i4Inc = 0; i4Inc < CMD_STR_WORDS; i4Inc ++)
    {
        pu1cmdArgs[i4Inc] = (CHR *)malloc(CMD_WORD_LEN);
        if (pu1cmdArgs[i4Inc] == NULL)
        {
            MEM_LLOC_ERR(FAILURE);
        }
        MEMSET(pu1cmdArgs[i4Inc], 0, CMD_WORD_LEN);
    }
    
    /* split cmd str*/
    i4Inc = 0;
    pu1CmdWord[i4Inc] = strtok(pu1CmdStr, " ");
    while(pu1CmdWord[i4Inc] != NULL)
    {
        i4Inc ++;
        pu1CmdWord[i4Inc] = strtok(NULL, " ");
    }

    if (eCurCmdLevel == CMD_LEVEL_ROOT)
    {
        i4CmdId = match_cmdInput(pu1CmdWord, pu1cmdArgs, &i4ArgNum);

        if (i4CmdId < 0)
        {
            PRINTF(" * invalid command.\n");
            return COMMAND_ERR;
        }

        i4Ret = armSdkCmdFuncs[i4CmdId](i4ArgNum, (const char **)pu1cmdArgs);
    }
    else if (eCurCmdLevel == CMD_LEVEL_MODULE)
    {
        ARM_CMD_IS_SUBMODULE("uart")
        {
            i4CmdId = uartMatchCmd(pu1CmdWord, pu1cmdArgs, &i4ArgNum);
            if (i4CmdId < 0)
            {
                PRINTF(" * invalid command.\n");
                return COMMAND_ERR;
            }

            i4Ret = uartCmdFuncs[i4CmdId](i4ArgNum, (const char **)pu1cmdArgs);
        }
    }

    for (i4Inc = 0; i4Inc < CMD_STR_WORDS; i4Inc ++)
    {
        free(pu1cmdArgs[i4Inc]);
        pu1cmdArgs[i4Inc] = NULL;
    }

    return i4Ret;
}




